package com.acooly.module.openapi.client.provider.fuyou.utils;

import com.acooly.core.utils.Encodes;
import com.acooly.core.utils.Strings;
import com.google.common.collect.Maps;

import javax.servlet.ServletRequest;
import java.util.*;

public class StringHelper {
    /**
     * 组装form表单
     *
     * @param url
     * @param params
     * @return
     */
    public static String netbankBuildFormHtml(String url, Map<String, String> params, String title) {
        StringBuffer html = new StringBuffer();
        html.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01Transitional//EN\">");
        html.append("正在跳转。。。<br/>");
        html.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/><title>" + title + "</title></head>");
        StringBuffer formhtml = new StringBuffer();
        formhtml.append("<form accept-charset=\"utf-8\" id=\"epayredirect\" name=\"epayredirect\" action=\"" + url
                + "\" method=\"post\">");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            formhtml.append(
                    "<input type=\"hidden\" name=\"" + entry.getKey() + "\" value=\"" + entry.getValue() + "\"/>");
        }

        formhtml.append("<input type=\"submit\" value=\"submit\" style=\"display:none;\"></form>");
        formhtml.append("<script>document.forms['epayredirect'].submit();</script>");
        html.append(formhtml.toString());
        html.append("<body></body></html>");
        return html.toString();
    }

    /**
     * @param strUrlParam
     * @return
     */
    public static Map<String, String> responseValue(String strUrlParam) {
        Map<String, String> mapRequest = new HashMap<>();

        String[] arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            // 解析出键值
            if (arrSplitEqual.length > 1) {
                // 正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    // 只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;

    }

    /**
     * 将map中的key和value转化为字符，并以index分开
     *
     * @param params
     * @return
     */
    public static String mapToStrByIndex(Map<String, Object> params, String index) {
        StringBuffer returnStr = new StringBuffer();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            returnStr.append(entry.getKey() + "=" + entry.getValue() + index);
        }
        return returnStr.substring(0, returnStr.length() - index.length());
    }

    /**
     * 将byte[] 转换成字符串
     *
     * @return
     */
    public static String byte2Hex(byte[] srcBytes) {
        StringBuilder hexRetSB = new StringBuilder();
        for (byte b : srcBytes) {
            String hexString = Integer.toHexString(0x00ff & b);
            hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
        }
        return hexRetSB.toString();
    }

    /**
     * 将16进制字符串转为转换成字符串
     *
     * @param source
     * @return
     */
    public static byte[] hex2Bytes(String source) {
        byte[] sourceBytes = new byte[source.length() / 2];
        for (int i = 0; i < sourceBytes.length; i++) {
            sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16);
        }
        return sourceBytes;
    }

    /**
     * 组装跳转url
     *
     * @param redirectUrl
     * @param redirectParams
     * @return
     */
    public static String getRedirectUrl(String redirectUrl, Map<String, String> redirectParams) {
        StringBuffer stringBuffer = new StringBuffer();
        for (Map.Entry<String, String> entry : redirectParams.entrySet()) {
            stringBuffer.append(entry.getKey() + "=" + Encodes.urlEncode(entry.getValue()) + "&");
        }
        return redirectUrl + "?" + stringBuffer.substring(0, stringBuffer.length() - 1);
    }

    public static String getRequestStr(SortedMap<String, String> requestDataMap) {
        Iterator<Map.Entry<String, String>> entries = requestDataMap.entrySet().iterator();
        StringBuilder returnStr = new StringBuilder();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            returnStr.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (Strings.isNotBlank(returnStr.toString())) {
            return returnStr.substring(0, returnStr.length() - 1);
        } else {
            return null;
        }
    }

    /**
     * 解析a=1&b=2的字符串
     * @param queryString
     * @return
     */
    public static Map<String,String> getParamsMap(String queryString) {
        Map<String,String> paramsMap = Maps.newHashMap();
        if (queryString != null && queryString.length() > 0) {
            int ampersandIndex, lastAmpersandIndex = 0;
            String subStr, param, value;
            String[] paramPair;
            do {
                ampersandIndex = queryString.indexOf('&', lastAmpersandIndex) + 1;
                if (ampersandIndex > 0) {
                    subStr = queryString.substring(lastAmpersandIndex, ampersandIndex - 1);
                    lastAmpersandIndex = ampersandIndex;
                } else {
                    subStr = queryString.substring(lastAmpersandIndex);
                }
                paramPair = subStr.split("=");
                param = paramPair[0];
                value = paramPair.length == 1 ? "" : paramPair[1];
                paramsMap.put(param, value);
            } while (ampersandIndex > 0);
        }
        return paramsMap;
    }

    /**
     * 异步通知请求参数转map
     * @return
     */
    public static Map<String, String> getNotifyParameters(ServletRequest request) {
        Map<String, String> params = new TreeMap<>();
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String[] values = request.getParameterValues(name);
            if (values == null || values.length == 0) {
                continue;
            }
            String value = values[0];
            // 注意：这里是判断不为null,没有包括空字符串的判断。
            if (value != null) {
                params.put(name, value);
            }
        }
        return params;
    }
}